<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="SalesPersonForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="关联钉钉" v-bind="validateInfos.name" id="SalesPersonForm-id" name="userid">
                <j-search-select v-model:value="formData.userid" dict="gbt_integral_user,name,userid" placeholder="关联钉钉"  allow-clear />
              </a-form-item>
            </a-col>
						<a-col :span="24">
							<a-form-item label="姓名" v-bind="validateInfos.name" id="SalesPersonForm-name" name="name">
								<a-input :disabled="true" v-model:value="formData.name" placeholder="请输入姓名"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="手机号" v-bind="validateInfos.phone" id="SalesPersonForm-phone" name="phone">
								<a-input v-model:value="formData.phone" placeholder="请输入手机号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
<!--						<a-col :span="24">-->
<!--							<a-form-item label="关联区域表" v-bind="validateInfos.regionId" id="SalesPersonForm-regionId" name="regionId">-->
<!--								<j-area-linkage v-model:value="formData.regionId" placeholder="请输入关联区域表" saveCode="region"  allow-clear />-->
<!--							</a-form-item>-->
<!--						</a-col>-->
						<a-col :span="24">
							<a-form-item label="岗位" v-bind="validateInfos.positionId" id="SalesPersonForm-positionId" name="positionId">
								<j-dict-select-tag v-model:value="formData.positionId" dictCode="f_sales_position,position_name,id" placeholder="请选择岗位"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="业务类型，预留" v-bind="validateInfos.businessType" id="SalesPersonForm-businessType" name="businessType">
								<a-input v-model:value="formData.businessType" placeholder="请输入业务类型，预留"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="状态" v-bind="validateInfos.status" id="SalesPersonForm-status" name="status">
								<j-dict-select-tag v-model:value="formData.status" dictCode="employment_status" placeholder="请选择状态"  allow-clear />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JAreaLinkage from '/@/components/Form/src/jeecg/components/JAreaLinkage.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../SalesPerson.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',   
    phone: '',   
    regionId: '',   
    positionId: '',   
    businessType: '',   
    status: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    userid:[{ required: true, message: '请关联钉钉!'}],
    name: [{ required: true, message: '请输入姓名!'},],
    phone: [{ required: true, message: '请输入手机号!'},],
    positionId: [{ required: true, message: '请输入岗位!'},],
    status: [{ required: true, message: '请选择状态!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  // 监听关联钉钉字段变化，自动查询用户信息
  watch(() => formData.userid, async (newId) => {
    console.log('watch触发，newId:', newId)
    if (newId) {
      try {
        console.log('开始请求API，userid:', newId)
        const res = await defHttp.get({
          url: '/hr/gbtIntegralUser/queryByuserid',
          params: { userid: newId }
        });
        console.log('API响应:', res)
        if (res) {
          const userInfo = res;
          console.log('用户信息:', userInfo)
          // 更新姓名和手机号
          formData.name = userInfo.name || '';
          formData.phone = userInfo.mobile || '';
          console.log('更新后的formData:', { name: formData.name, phone: formData.phone })
        } else {
          console.log('API响应格式不正确:', res)
        }
      } catch (error) {
        console.error('查询用户信息失败:', error);
        createMessage.warning('查询用户信息失败');
      }
    } else {
      console.log('清空钉钉选择，清空姓名和手机号')
      // 清空姓名和手机号
      formData.name = '';
      formData.phone = '';
    }
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch (error: any) {
      if (error?.errorFields) {
        const firstField = error.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(error);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
